# encrypt [input] cyphertext [output]
import sys
import string
def encrypt(infile , key, outfile):
	print "===================== ENCRYPT VIGENERE ======================"
	input = string.upper(open(infile, "r").read())
	key = string.upper(key)
	i = 0
	output = ''
	for c in input:
		if ord(c) in range(ord('A'), ord('Z')+1):
			output = output + encrypt_char(c, key[i%len(key)])
			i = i + 1
		else:
			output = output + c
	outfile = open(outfile, "w")
	outfile.write(output)
	outfile.close()

def decrypt(infile , key, outfile):
	print "===================== ENCRYPT VIGENERE ======================"
	input = string.upper(open(infile, "r").read())
	key = string.upper(key)
	i = 0
	output = ''
	for c in input:
		if ord(c) in range(ord('A'), ord('Z')+1):
			output = output + decrypt_char(c, key[i%len(key)])
			i = i + 1
		else:
			output = output + c
	outfile = open(outfile, "w")
	outfile.write(output)
	outfile.close()

def value_char(input_char):
	return ord(input_char) - 65
def encrypt_char(input_char, key_char):
	return chr((value_char(input_char) + value_char(key_char)) % 26 + 65)
def decrypt_char(output_char, key_char):
	return chr((value_char(output_char)+26 - value_char(key_char)) % 26 + 65)

if (len(sys.argv) < 5):
	print "Use: \n\tvigenere.py -e [file_input] [key] [file_output]"
	sys.exit()
if(sys.argv[1] == "-e"):
	encrypt(sys.argv[2], sys.argv[3], sys.argv[4]);
elif(sys.argv[1] == "-d"):
	decrypt(sys.argv[2], sys.argv[3], sys.argv[4]);